// Parse SRT text
function handleSRT(content) {
  content.push("");
  content.push("-->");
  let group = [];
  let lastFormat = 0;
  for (let i = 0;i < content.length;i++) {
    if (content[i].indexOf("-->") !== -1) {
      if (lastFormat === 0) {
        lastFormat = i;
        continue;
      }
      let time = content[lastFormat].replace(/ /g, "");
      let startTime = time.split("-->")[0];
      let endTime = time.split("-->")[1];
      let parsed_startTime = transformToHtmlCurrentTime(startTime);
      let parsed_endTime = transformToHtmlCurrentTime(endTime);
      group.push({
        id: content[lastFormat - 1],
        startTime: {
          baseForm: startTime,
          hour: parsed_startTime.hour,
          minute: parsed_startTime.minute,
          second: parsed_startTime.second,
          millisecond: parsed_startTime.millisecond,
          htmlCurrentTime: (parsed_startTime.hour * 3600) + (parsed_startTime.minute * 60) + parsed_startTime.second + (parsed_startTime.millisecond / 1000),
        },
        endTime: {
          baseForm: endTime,
          hour: parsed_endTime.hour,
          minute: parsed_endTime.minute,
          second: parsed_endTime.second,
          millisecond: parsed_endTime.millisecond,
          htmlCurrentTime: (parsed_endTime.hour * 3600) + (parsed_endTime.minute * 60) + parsed_endTime.second + (parsed_endTime.millisecond / 1000),
        },
        content: mergeText(content, lastFormat, i)
      });
      lastFormat = i;
    }
  }
  return group;
}

function transformToHtmlCurrentTime(time) {
  let hour = parseInt(time.split(":")[0]);
  let minute = parseInt(time.split(":")[1]);
  let second = parseInt(time.split(":")[2].split(",")[0]);
  let millisecond = parseInt(time.split(":")[2].split(",")[1]);
  return {
    hour, minute, second, millisecond
  };
}

function mergeText(content, lastFormat, nowFormat) {
  let text = "";
  for (let i = lastFormat + 1;i < nowFormat - 1;i++) {
    text += content[i];
    if (i < nowFormat - 2) {
      text += "\n"
    }
  }
  return text;
}

module.exports = handleSRT;